package datatype

import (
	"encoding/binary"
	"math"
	"strconv"
)

//DeadbandConst 死区的最小常量
const DeadbandConst = 0.000000000001

//FloatEqual 浮点数据判断值是否相等
func FloatEqual(a, b float64) bool {
	return math.Abs(a-b) < DeadbandConst
}

//Float32Equal 浮点数据判断值是否相等
func Float32Equal(a, b float64) bool {
	return math.Abs(a-b) < 0.000001
}

//Deadband 死区判断，判断是否在死区范围内
func Deadband(a, b, c float64) bool {
	return math.Abs(a-b) < c
}

//Convert3412 转换ABCD 格式
func Convert3412(b []byte) {
	_ = b[3]
	b[2], b[3], b[0], b[1] = b[0], b[1], b[2], b[3]
	return
}

//Convert3412Bytes float 转换为字节数组
func Convert3412Bytes(value float64) []byte {
	buf := make([]byte, 4)
	ival := math.Float32bits(float32(value))
	binary.BigEndian.PutUint32(buf, ival)
	Convert3412(buf)
	return buf
}

//Convert3412Float32 转换为3412 类型的浮点型
func Convert3412Float32(b []byte) (val float64) {
	Convert3412(b)
	val = float64(math.Float32frombits(binary.BigEndian.Uint32(b)))
	return
}

//ConvertBigEndianFloat32 从字节数组中转换大编码float
func ConvertBigEndianFloat32(b []byte) (val float64) {
	val = float64(math.Float32frombits(binary.BigEndian.Uint32(b)))
	return
}

//ConvertLittleEndianFloat32 从字节数组中转换大编码float
func ConvertLittleEndianFloat32(b []byte) (val float64) {
	val = float64(math.Float32frombits(binary.LittleEndian.Uint32(b)))
	return
}

//ToString 浮点类型转字符串
func ToString(val float64) string {
	return strconv.FormatFloat(val, 'f', -1, 64)
}
